package dapps.web.proj;

import java.util.List;

import javax.servlet.ServletContext;

import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springside.modules.orm.Page;
import org.springside.modules.web.struts2.CRUDActionSupport;
import org.springside.modules.web.struts2.Struts2Utils;

import dapps.entity.proj.Type;
import dapps.service.ServiceException;
import dapps.service.proj.TypeManager;

/**
 * 项目类型管理Action.
 * 
 * 使用Struts2 convention-plugin annotation定义Action参数.

 */
@SuppressWarnings("serial")
@Results( { @Result(name = CRUDActionSupport.RELOAD, location = "type.action", type = "redirect") })
public class TypeAction extends CRUDActionSupport<Type> {

	@Autowired
	private TypeManager typeManager;


	// 基本属性
	private Type entity;
	private Long id;
	private List<Type> allTypes;
	private Page<Type> page = new Page<Type>(200);
	String ordername;



	// 基本属性访问函数 //

	public Type getModel() {
		return entity;
	}

	@Override
	protected void prepareModel() throws Exception {
		if (id != null) {
			entity = typeManager.get(id);
		} else {
			entity = new Type();
		}
		
	}

	public void setId(Long id) {
		this.id = id;
	}
	public void setOrdername(String ordername) {
		this.ordername = ordername;
	}
	public List<Type> getAllTypes() {
		return allTypes;
	}
	
	public Page<Type> getPage() {
		return page;
	}

	// CRUD Action 函数 //

	@Override
	public String list() throws Exception {
		allTypes = typeManager.getAllTypesOrder();
		return SUCCESS;
	}


	@Override
	public String save() throws Exception {		
		typeManager.save(entity);
		refreshapplication();
		addActionMessage("保存项目类型成功");
		return RELOAD;
	}
	
	public void refreshapplication() throws Exception {
		ServletContext application = Struts2Utils.getApplication();
		if(application.getAttribute("allTypesOrder")!=null){			
			synchronized(application){
				application.removeAttribute("allTypesOrder");
				application.setAttribute("allTypesOrder", typeManager.getAllTypesChoose());
			}
		}
	}
	@Override
	public String delete() throws Exception {
		try {
			typeManager.delete(id);
			refreshapplication();
			addActionMessage("删除项目类型成功");
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			addActionMessage(e.getMessage());
		}
		return RELOAD;
	}


}